﻿using Mengsk.ERP.Orders;
using mshtml;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ERP.App.Orders
{
    /// <summary>
    /// Interaction logic for OrderDeliveryYT.xaml
    /// </summary>
    public partial class OrderDeliveryYT : UserControl, IUIPlugin
    {
        private string ORDER_INJECT_FILE = System.IO.Path.Combine(new FileInfo(typeof(OrderDeliveryYT).Assembly.Location).DirectoryName, "JS\\OrderInject.js");
        private const string INJECT_JS = "function fixahref(){$(\"a\").each(function(index){$(this).attr(\"target\",\"_self\");});} function noError(){return true;} window.onerror=noError;function myInjectMac(){$(\"#visitorMac\").val(\"B8-97-5A-31-4A-5D\");var client=new Object();client[\"macs\"]=\"B8-97-5A-31-4A-5D\";client[\"cpuId\"]=\"123fds\"; $.cookie('mac', JSON.stringify(client), {path: '/'});}";
        private System.Collections.ObjectModel.ObservableCollection<string> deliveryNumbers = new System.Collections.ObjectModel.ObservableCollection<string>();

        private bool myLoaded = false;

        public OrderDeliveryYT()
        {
            InitializeComponent();
        }

        public string Title
        {
            get { return "圆通金刚系统"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (myLoaded)
            {
                return;
            }
            myLoaded = true;
            this.wb1.Navigate("http://jingang.yto56.com.cn/ord/logout.action");
            this.wb1.Navigating += wb1_Navigating;
            this.wb1.LoadCompleted += wb1_LoadCompleted;
            this.listDeliveryNumber.ItemsSource = this.deliveryNumbers;
        }

        void wb1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            this.btnInjectMac.IsEnabled = false;
        }

        void wb1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            this.btnInjectMac.IsEnabled = true;
            HTMLDocument doc2 = this.wb1.Document as HTMLDocument;
            IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT");
            scriptErrorSuppressed.type = "text/javascript";
            scriptErrorSuppressed.text = INJECT_JS;
            IHTMLElementCollection nodes = doc2.getElementsByTagName("head");

            IHTMLScriptElement queryOrder = (IHTMLScriptElement)doc2.createElement("SCRIPT");
            queryOrder.type = "text/javascript";
            queryOrder.text = File.ReadAllText(ORDER_INJECT_FILE, Encoding.Unicode);

            foreach (IHTMLElement elem in nodes)
            {
                HTMLHeadElement head = (HTMLHeadElement)elem;
                head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
                head.appendChild((IHTMLDOMNode)queryOrder);
            }
        }

        private void btnInjectMac_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.wb1.InvokeScript("myInjectMac");
                this.wb1.InvokeScript("fixahref");
                string macId = "visitorMac";
                HTMLDocument doc2 = this.wb1.Document as HTMLDocument;
                var item = doc2.getElementById(macId) as IHTMLInputHiddenElement;
                if (item != null)
                {
                    Console.WriteLine(item.value);
                }
                MessageBox.Show("注入成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "注入失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string QueryOrderId(string ppcod)
        {
            var obj = this.wb1.InvokeScript("mengsk_search_ppcod", ppcod);
            string text = obj == null ? "" : obj.ToString();

            if (this.tbMessage.LineCount > 100000)
            {
                this.tbMessage.Text = "";
            }
            if (obj == null)
            {
                this.tbMessage.AppendText(DateTime.Now + ":JavaScript方法没有返回值");
                return "false";
            }
            else
            {
                this.tbMessage.AppendText(DateTime.Now + ":" + text);
            }

            if (obj == null)
            {
                MessageBox.Show("查找数据失败:JavaScript方法没有返回值");
                return "";
            }

            //从数据中提取物流公司对应的ID
            int ppcodIndex = text.LastIndexOf(ppcod);
            if (ppcodIndex < 0)
            {
                MessageBox.Show("无法根据PPCOD找到对应物流订单");
                return "";
            }

            //向前搜索圆通公司的OrderID
            int lastIndex = -1;
            int currentIndex = 0;
            while (currentIndex < ppcodIndex)
            {
                currentIndex = text.IndexOf("orderId", currentIndex);
                if (currentIndex < 0)
                {
                    break;
                }
                Debug.WriteLine(text.Substring(currentIndex, 50));
                if (currentIndex >= ppcodIndex)
                {
                    break;
                }
                lastIndex = currentIndex;
                currentIndex += "orderId".Length;
            }

            if (lastIndex < 0)
            {
                MessageBox.Show("无法根据PPCOD找到对应物流订单");
                return "";
            }

            //找到了
            int spaceIndex = text.IndexOf("\"", lastIndex + "orderId=\"".Length);
            if (spaceIndex < 0)
            {
                MessageBox.Show("返回数据有错误,无法找到\"结束符");
                return "";
            }

            string orderId = text.Substring(lastIndex + "orderId=\"".Length, spaceIndex - lastIndex - "orderId=\"".Length);
            return orderId;
        }


        private void btnCallQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string orderId = this.QueryOrderId("PPCOD1100775024");
                MessageBox.Show("测试PPCOD:PPCOD1100775024,对应圆通订单号:" + orderId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "注入失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void tbDeliveryNumber_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key != Key.Enter)
                {
                    return;
                }
                e.Handled = true;
                string number = this.tbDeliveryNumber.Text.Trim();
                if (String.IsNullOrWhiteSpace(number))
                {
                    return;
                }

                if (number.Length != 10 || number[0] != 'D')
                {
                    throw new Exception("快递单号必须为10为,且以D开头");
                }

                if (this.deliveryNumbers.Contains(number))
                {
                    throw new Exception("订单已经扫描");
                }

                Order[] orders = OrderManager.Instance.GetOrdersByDeliveryNumber(number);
                if (orders == null || orders.Length < 1)
                {
                    throw new Exception("订单在本地ERP中不存在");
                }

                if (orders.Length > 1)
                {
                    throw new Exception("订单在本地ERP中找到多个订单");
                }

                Order order = orders[0];
                if (string.IsNullOrWhiteSpace(order.PPCOD))
                {
                    throw new Exception("订单的PPCOD为空");
                }
                string orderId = this.QueryOrderId(order.PPCOD);

                if (string.IsNullOrWhiteSpace(orderId) || orderId.Length < 20)
                {
                    throw new Exception("订单在圆通系统中不存在,请检查订单PPCOD是否正确!!!");
                }

                object ret = this.wb1.InvokeScript("mengsk_markdelivery", orderId, number);
                if (ret == null)
                {
                    throw new Exception("发货标记失败,JS返回值为空");
                }

                string strRet = ret.ToString();
                if (strRet.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
                {
                    this.deliveryNumbers.Add(number);
                    this.tbHistory.Text = "扫描数量:" + this.deliveryNumbers.Count;
                    this.tbDeliveryNumber.Text = "";
                }
                else
                {
                    throw new Exception(strRet);
                }
            }
            catch (Exception ex)
            {
                this.tbDeliveryNumber.Text = "";
                MessageBox.Show(ex.Message, "发货失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
